package woa.linkedlist;

/**
 * 循环链表
 *
 * @author wangpeng
 * @date 2022/1/6
 */
public class MyCircleLinkedList {

    private Node head;

    private Node tail;

    private int count;

    public MyCircleLinkedList() {

    }

    public class Node {

        public int val;
        public Node next;

        public Node() {
        }

        public Node(int val) {
            this.val = val;
        }

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }

    }

    public int get(int index) {
        if (count == 0 || index > count - 1 || index < 0) {
            return -1;
        }
        Node cur = head;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        return cur.val;
    }

    public void addAtHead(int val) {
        Node cur = new Node(val);
        if (count == 0) {
            head = tail = cur;
        } else {
            cur.next = head;
            head = cur;
        }
        tail.next = head;
        count++;
    }

    public void addAtTail(int val) {
        Node cur = new Node(val);
        if (count == 0) {
            head = tail = cur;
        } else {
            tail.next = cur;
            tail = cur;
        }
        tail.next = head;
        count++;
    }

    public void deleteAtIndex(int index) {
        if (count == 0 || index > count - 1 || index < 0) {
            return;
        }
        if (index == 0) {
            head = head.next;
            if (index == count - 1) {
                tail = head = null;
            } else {
                tail.next = head;
            }
        } else {
            Node cur = head;
            for (int i = 1; i < index; i++) {
                cur = cur.next;
            }
            cur.next = cur.next.next;
            if (index == count - 1) {
                tail = cur;
            }
            tail.next = head;
        }
        count--;
    }

    public static void main(String[] args) {
        MyCircleLinkedList linkedList = new MyCircleLinkedList();
        linkedList.addAtHead(1);
        linkedList.addAtTail(3);
        linkedList.get(1);            //返回3
        linkedList.deleteAtIndex(1);  //现在链表是1
        linkedList.get(0);            //返回1
    }
}
